package com.usefullc.blog.controller;

import com.usefullc.blog.domain.*;
import com.usefullc.blog.enums.ArticleStatusEnum;
import com.usefullc.blog.param.ReplyParam;
import com.usefullc.blog.query.ArticleLikeQuery;
import com.usefullc.blog.query.ArticleQuery;
import com.usefullc.blog.query.ReplyQuery;
import com.usefullc.blog.query.TagQuery;
import com.usefullc.blog.service.*;
import com.usefullc.blog.vo.ArticleVo;
import com.usefullc.blog.vo.CategoryVo;
import com.usefullc.blog.vo.ReplyVo;
import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.user.OnlineUser;
import com.usefullc.common.user.OnlineUserManager;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.common.util.RequestUtils;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.entity.WebResult;
import com.usefullc.system.param.IdParam;
import com.usefullc.system.param.IdsParam;
import com.usefullc.system.service.component.extend.ExtendDataComponent;
import com.usefullc.system.validator.UsefulValid;
import com.usefullc.user.service.UserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Sampson
 * @date: 2022-07-07 21:01
 */
@Controller
@RequestMapping("/cmsBlog")
@Api( tags="博客前端页面")
public class BlogController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ExtendDataComponent extendDataComponent;

    @Autowired
    private ArticleReadService articleReadService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private ReplyLikeService replyLikeService;

    @Autowired
    private ArticleLikeService articleLikeService;

    @Autowired
    private ArticleShareService articleShareService;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;


    @GetMapping({"/","","/index.html"})
    public String index( Model model) {
        return "public/index.html";
    }

    @GetMapping({"/register.html"})
    public String register( Model model) {
        return "public/register.html";
    }

    @GetMapping({"/login.html"})
    public String login( Model model) {
        return "public/login.html";
    }

    @GetMapping({"/logout.html"})
    public String logout(HttpServletRequest request, Model model) {
        userService.clearLoginUser(request);
        return "public/login.html";
    }


    @GetMapping({"/about.html"})
    public String about( Model model) {
        return "public/about.html";
    }

    @GetMapping("/category/{sid}.html")
    public String articleList(@PathVariable("sid") String sid, Model model) {
        ArticleQuery articleQuery = new ArticleQuery();
        Long categoryId;
        if(sid.indexOf("-") > 0){
            categoryId = Long.valueOf(sid.split("-")[0]);
            articleQuery.setPageIndex(Integer.valueOf(sid.split("-")[1]));
        }else{
            categoryId = Long.valueOf(sid);
        }

        Category category = categoryService.findById(categoryId);
        CategoryVo categoryVo = BeanUtils.beanCopy(category,CategoryVo.class);
        categoryVo.setUrlPrefix(StringUtils.removeEnd(category.getUrl(),".html"));
        model.addAttribute("category",categoryVo);

        List<Category> childCategoryList = categoryService.getChildrenByCodeLike(category.getCode());
        List<Long> categoryIds = childCategoryList.stream().map(data -> data.getId()).collect(Collectors.toList());

        //获取文章列表
        categoryIds.add(categoryId);
        articleQuery.setCategoryIds(categoryIds);
        articleQuery.setStatus(ArticleStatusEnum.RELEASED.getCode());
        articleQuery.setOrderByColumn("top,gmtCreate");
        articleQuery.setAscOrDesc("desc");
        Pager<ArticleVo> pager = articleService.findCmsVoByPage(articleQuery);

        model.addAttribute("pager",pager);

        return "public/list.html";
    }


    @GetMapping("/tag/{tagId}.html")
    public String tagArticleList(@PathVariable("tagId") Long tagId, Model model) {
        TagQuery tagQuery = new TagQuery();
        tagQuery.setId(tagId);
        Pager<ArticleVo> pager = articleService.findCmsPageVoByTag(tagQuery);
//        ArticleQuery articleQuery = new ArticleQuery();
//        Long categoryId;
//        if(sid.indexOf("-") > 0){
//            categoryId = Long.valueOf(sid.split("-")[0]);
//            articleQuery.setPageIndex(Integer.valueOf(sid.split("-")[1]));
//        }else{
//            categoryId = Long.valueOf(sid);
//        }

//        Category category = categoryService.findById(categoryId);
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setUrlPrefix("/cmsBlog/tag/"+tagId);
        categoryVo.setUrl("/cmsBlog/tag/"+tagId+".html");
        Tag tag = this.tagService.findById(tagId);
        categoryVo.setName(tag.getName());
//        categoryVo.setUrlPrefix(StringUtils.removeEnd(category.getUrl(),".html"));
        model.addAttribute("category",categoryVo);

//        List<Category> childCategoryList = categoryService.getChildrenByCodeLike(category.getCode());
//        List<Long> categoryIds = childCategoryList.stream().map(data -> data.getId()).collect(Collectors.toList());

//        //获取文章列表
//        categoryIds.add(categoryId);
//        articleQuery.setCategoryIds(categoryIds);
//        articleQuery.setStatus(ArticleStatusEnum.RELEASED.getCode());
//        Pager<ArticleVo> pager = articleService.findCmsVoByPage(articleQuery);

        model.addAttribute("pager",pager);

        return "public/list.html";
    }



    @GetMapping("/article/{articleId}.html")
    public String article(@PathVariable("articleId") Long articleId, Model model, HttpServletRequest request) {

        Article article = this.articleService.findById(articleId);

        //记录阅读数量
        articleService.doRead(articleId);

        Long categoryId = article.getCategoryId();

        Category category = categoryService.findById(categoryId);
        model.addAttribute("category",category);

        if(category.getParentId() == 0){
            Category parentCategory = new Category();
            parentCategory.setUrl("/");
            parentCategory.setName("首页");
            model.addAttribute("parentCategory",parentCategory);
        }else{
            Category parentCategory = categoryService.findById(category.getParentId());
            model.addAttribute("parentCategory",parentCategory);
        }

        model.addAttribute("article",articleService.wrapperCmsArticle(article));

        ArticleQuery articleQuery = new ArticleQuery();

        String gmtCreateTime = DateFormatUtils.format(article.getGmtCreate(),"yyyy-MM-dd HH:mm:ss");
        articleQuery.setGmtCreateSecondStart(gmtCreateTime);
        articleQuery.setCategoryId(categoryId);
        articleQuery.setResultLimit(1);
        Article preArticle = articleService.findOne(articleQuery);
        model.addAttribute("preArticle",articleService.wrapperCmsArticle(preArticle));

        articleQuery = new ArticleQuery();
        articleQuery.setGmtCreateSecondEnd(gmtCreateTime);
        articleQuery.setCategoryId(categoryId);
        articleQuery.setResultLimit(1);
        Article nextArticle = articleService.findOne(articleQuery);
        model.addAttribute("nextArticle",articleService.wrapperCmsArticle(nextArticle));


        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            model.addAttribute("logined",false);
        }else{
            //点赞
            model.addAttribute("logined",true);
            model.addAttribute("user",loginUser);
//            model.addAttribute("userId",loginUser.getUserId());
            ArticleLikeQuery articleLikeQuery = new ArticleLikeQuery();
            articleLikeQuery.setUserId(loginUser.getUserId());
            articleLikeQuery.setArticleId(articleId);
            articleLikeQuery.setStatus(YesNoEnum.YES.getCode());
            ArticleLike articleLike = articleLikeService.findOne(articleLikeQuery);
            if(articleLike != null){
                model.addAttribute("liked",true);
            }

            articleLikeQuery = new ArticleLikeQuery();
            articleLikeQuery.setArticleId(articleId);
            articleLikeQuery.setStatus(YesNoEnum.YES.getCode());
            long likeNum = articleLikeService.count(articleLikeQuery);
            model.addAttribute("likeNum",likeNum);

            //评论
            ReplyQuery replyQuery = new ReplyQuery();
            replyQuery.setArticleId(articleId);
            replyQuery.setUserId(loginUser.getUserId());
            long replyNum = replyService.count(replyQuery);
            model.addAttribute("replyNum",replyNum);

            replyQuery = new ReplyQuery();
            replyQuery.setArticleId(articleId);
            List<ReplyVo> replyDataList = replyService.findVoByPage(replyQuery).getDataList();

            model.addAttribute("replyDataList",replyDataList);
        }

        return "public/info.html";
    }


    //阅读
    //点赞
    @ResponseBody
    @PostMapping({"/like"})
    public WebResult like(@UsefulValid @RequestBody IdParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        boolean result = articleLikeService.like(param.getId(),loginUser.getUserId(), RequestUtils.getClientIpAddr());
        return WebResultBuilder.successResult(result);
    }

    @ResponseBody
    @PostMapping({"/unLike"})
    public WebResult unLike(@UsefulValid @RequestBody IdParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        boolean result = articleLikeService.unLike(param.getId(),loginUser.getUserId());
        return WebResultBuilder.successResult(result);
    }

    //回复
    @ResponseBody
    @PostMapping({"/reply"})
    public WebResult reply(@UsefulValid(save = true) @RequestBody ReplyParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }

        Reply reply = BeanUtils.beanCopy(param,Reply.class);
        reply.setUserId(loginUser.getUserId());
        boolean result = replyService.save(reply);
        return WebResultBuilder.successResult(result);
    }
    //删除回复
    //回复列表




}
